<script setup lang="ts">
import { Plus, Delete } from '@element-plus/icons-vue';
import { difference } from 'lodash-es';
import baseSearch from '@/components/base-ui/base-search/index.vue';
import baseTable from '@/components/base-ui/base-table/index.vue';
import Modal from '@/components/q-modal/index.vue';
import updateDialog from './dialog/update/index.vue';
import { message } from '@/components/q-message/message';
import { searchConfig } from './config/search-config';
import { tableConfig } from './config/table-config';
import { doGetSupplierList, doDelSupplier } from '@/api/base/supplier/index';
import { handleChildren } from '@/utils/common';
import type { SupplierRecords } from '@/api/base/supplier/model/type';
import addDataStore from '@/store/modules/addDataStore';

const router = useRouter();

const { handleAddData } = addDataStore();

defineOptions({
    name: 'supplierList'
});

const tableRef = ref<TableRef>();

const searchRef = ref<InstanceType<typeof baseSearch>>();

/**
 * @: 处理列表子父级
 */
const handleTableData = ({ records }: { records: SupplierRecords[] }) => {
    return handleChildren(records, 'id', {
        supplierCode: '',
        supplierPerson: '',
        supplierPhone: '',
        supplierName: ''
    });
};

/**
 * @: 复选框选中
 */
let preSelect: string[] = [];
const selectIds = ref<string[]>([]);
const handleSelection = (suppliers: SupplierRecords[]) => {
    const selectList = suppliers.filter(item => item.supplierCode);
    const selects = selectList.map(item => item.id);

    // 如果上次选中的id比本次选择的id多就是取消勾选
    if (preSelect.length > selects.length) {
        selectIds.value = difference([...new Set(selects)], result(preSelect, selects));
    } else {
        selectIds.value = [...new Set(selects)];
    }

    // 如果没有选中的id把全部复选框清空
    if (!selectIds.value.length) {
        tableRef.value?.clearSelection();
    }
    preSelect = selects;
};

/**
 * @: 筛选出新增的数据
 */
function result(allVal: string[], delVal: string[]) {
    for (let i = 0; i < delVal.length; i++) {
        const ind = allVal.findIndex(it => it === delVal[i]);
        if (ind !== -1) {
            allVal.splice(ind, 1);
        }
    }
    return allVal;
}

/**
 * @: 删除父级
 */
const delParent = () => {
    Modal.confirm({
        title: '确认删除',
        content: `选中${selectIds.value.length}行数据，删除后无法恢复，确认删除？`,
        width: '380px',
        onOk: async () => {
            try {
                await handleDel({ supplierIds: selectIds.value.join(',') });

                getTableData(); // 清空所有选择选项
            } catch (error) {
                return console.log('Oops errors!');
            }
        }
    });
};

/**
 * @: 删除子级
 */
const delChildren = async (row: SupplierRecords) => {
    if (row.supplierCode && !row.children.length) {
        handleDel({ supplierIds: row.id });
    } else {
        handleDel({ supplierIds: row.id, materialId: row.materialId });
    }
};

/**
 * @: 删除操作
 */
const handleDel = async (params: { supplierIds?: string; materialId?: string }) => {
    try {
        const { code } = await doDelSupplier(params);
        if (code === 200) {
            message.success('删除成功');
            getTableData();
        }
    } catch (error) {
        console.log('error', error);
    }
};

/**
 * 新增
 */
const handleAdd = () => {
    handleAddData('supplerAddData');
    router.push('/supplier/add');
};

/**
 * 编辑
 */
const updateRef = ref<InstanceType<typeof updateDialog>>();
const handleEdit = (row: SupplierRecords) => {
    updateRef.value?.open(row.id);
};

/**
 * 拉取表格数据
 */
const getTableData = async () => {
    let completeParams;
    if (searchRef.value) {
        completeParams = searchRef.value.getForm();
    }
    tableRef.value?.getData?.(completeParams);
};

// 禁用编辑
const editDisabledFn = (row: SupplierRecords) => row.supplierCode === '';

/**
 * @: 初始化时选中id
 */
const selectTableItem = () => {
    // 勾选子级和父级
    selectIds.value.forEach(item => {
        const obj = tableRef.value?.tableData.find((ite: SupplierRecords) => item === ite.id);
        if (obj) {
            tableRef.value?.toggleRowSelection(obj, true);
        }
    });

    // 取消勾选上次选中的
    tableRef.value?.elTable?.getSelectionRows().forEach((item: SupplierRecords) => {
        if (!selectIds.value.includes(item.id)) {
            tableRef.value?.toggleRowSelection(item, false);
        }
    });
};
</script>

<template>
    <q-page>
        <!-- 搜索 -->
        <base-search ref="searchRef" :table-ref="tableRef" :search-config="searchConfig" />

        <!-- 表格 -->
        <base-table
            ref="tableRef"
            :handle-table-data="handleTableData"
            :tableConfig="tableConfig"
            :get-data-fn="doGetSupplierList"
            :table-attr="{
                rowKey: 'supplierMaterialId',
                defaultExpandAll: true
            }"
            :edit-disabled-fn="editDisabledFn"
            class="hide-children-select"
            @load="selectTableItem"
            @selection-change="handleSelection"
            @del="delChildren"
            @edit="handleEdit"
        >
            <template #tableHeadStart>
                <el-button type="primary" :icon="Plus" @click="handleAdd"> 新增 </el-button>
            </template>
            <template #tableHeadEnd>
                <el-button
                    class="m-r-16"
                    :disabled="selectIds.length === 0"
                    :icon="Delete"
                    @click="delParent"
                >
                    删除
                </el-button>
            </template>

            <!-- 成品率 -->
            <template #finishedProductRate="{ row }">
                {{ (row.finishedProductRate ?? '0') + '%' }}
            </template>

            <!-- 准交率 -->
            <template #quasiDeliveryRate="{ row }">
                {{ (row.quasiDeliveryRate ?? '0') + '%' }}
            </template>
        </base-table>

        <!-- 新增和编辑 -->
        <update-dialog ref="updateRef" @update-success="getTableData" />
    </q-page>
</template>

<style scoped lang="scss">
@include b(hide-children-select) {
    // 隐层子级复选框
    :deep(.el-table__body-wrapper) {
        .el-table__row--level-1 {
            .el-checkbox {
                display: none;
            }
        }
    }
}
</style>
